package sundun.sharding.execution.impl;


import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.reflection.MetaObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sundun.sharding.config.TableConfiguration;
import sundun.sharding.factory.SqlSessionFactoryWrapper;

import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * query
 * @author: zxl
 * @date: 2024/8/11 11:40
 */
public class ReaderExecutionStrategy extends AbstractExecutionStrategy{

    private static final Logger logger = LoggerFactory.getLogger(ReaderExecutionStrategy.class);

    public ReaderExecutionStrategy(SqlSessionFactoryWrapper sqlSessionFactoryWrapper, Map<String, TableConfiguration> tableConfigurations) {
        super(sqlSessionFactoryWrapper, tableConfigurations);
    }

    @Override
    protected Object doExecute(Invocation invocation, TableConfiguration tableRule, MetaObject metaStatementHandler, MappedStatement mappedStatement) throws InvocationTargetException, IllegalAccessException {
        Object rest = null;
        if (tableRule.getReadSharding()){
            rest = invocation.proceed();
        }else{
            try {
                rest = invoke(invocation,metaStatementHandler,mappedStatement);
                if (rest != null && !(List.class.isAssignableFrom(rest.getClass()))){
                    List<Object> tmp = new ArrayList<>();
                    tmp.add(rest);
                    rest = tmp;
                }
                logger.info("【切换原库】-{reader}-查询原表数据！ invoke result {}",rest);
            } catch (NoSuchMethodException | SQLException e) {
                throw new RuntimeException("query exception ",e);
            }
        }
        return rest;
    }

}
